<?php
/**
 * Created by PhpStorm.
 * User: frankpian
 * Date: 18-4-19
 * Time: 下午2:09
 */

class FirmwareController extends CloudControllerBase
{

    public function listFirmwareVersionAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action)
        {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT v.*, t.name AS type_name, u.nickname  FROM firmware_version AS v 
                            LEFT JOIN firmware_type AS t ON v.firmware_type_id=t.id
                            LEFT JOIN user AS u ON v.created_user_id=u.id)";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "type_name" => "固件分类",
                    "name" => "固件名称",
                    "version" => "版本号",
                    "url" => "文件下载",
                    "size" => "大小",
                    "nickname" => "上传人",
                    "created_at" => "创建时间"
                ), $table
                    , array(
                        ["name", "like", "%", "%"],
                        ["version", "like", "%", "%"],
                        ["firmware_type_id", "="],
                        ['created_at_start', '>=', '', '', "created_at"],
                        ['created_at_end', '<=', '', '', "created_at"]
                    ),"created_at desc","id");
            };
                break;
        }
        $this->view->setVars(array("firmwareTypeList" => $this->getFirmwareTypeInfo()));
    }

    public function addFirmwareVersionAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $userId=$this->getMonitorLoginUser()->userId;
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_ADD:{
                $this->checkRequestParams(array(
                    array(
                        "key" => "name",
                        "type" => "presence",
                        "message" => "请输入固件名称"),
                    array(
                        "key" => "firmware_type_id",
                        "type" => "presence",
                        "message" => "请选择固件分类"),
                    array(
                        "key" => "url",
                        "type" => "presence",
                        "message" => "文件未上传"),

                ));
                $last_id = $this->insertSqlData(array(
                    "table" => "firmware_version",
                    "fieldList" => array("name", "version", "firmware_type_id", "url", "html", "size"),
                    "addItems" => array("created_user_id" => $userId)
                ));
                if ($last_id>0){
                    $this->returnSuccess("文件上传成功");
                }else{
                    $this->returnError("上传失败！");
                }
            };
                break;
            default:
                $this->view->setVars(array("firmwareTypeList" => $this->getFirmwareTypeInfo()));
                break;
        }
    }

    public function detailFirmwareVersionAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_UPDATE:
            {
                $keyId = $this->getPost("id");
                $sqlId = $this->updateSqlData(array(
                    "table" => "firmware_version",
                    "fieldList" => array("name", "version", "firmware_type_id", "url", "html"),
                    "where" => " id='$keyId' "
                ));
                $this->returnSuccess("发布或保存成功");
//                if ($sqlId){
//                    $this->returnSuccess("发布或保存成功");
//                }else{
//                    $this->returnError("发布或保存失败");
//                }
            }
                break;
            case $this::REQUEST_ACTION_DELETE:
            {
                $data = $this->getPost("filter_list");
                $keyId = json_decode($data, true)["id"];
                $data = $this->fetchOne("SELECT * FROM firmware_version WHERE id=$keyId");
                if ($data["url"]){
                    $this->deleteFileCos($data["url"]);
                }
                $result = $this->deleteOne("firmware_version", array("id"=>$keyId));
                if ($result>0){
                    $this->returnSuccess("删除成功！");
                }else{
                    $this->returnError("删除失败！");
                }
            }
                break;
            default:{
                $keyId = $this->getQuery("id");
                $sql = "SELECT * FROM firmware_version WHERE firmware_version.id=$keyId";
                $keyData = $this->fetchOne($sql);
                $this->view->setVars(array("data"=>$keyData));
                $this->view->setVars(array("firmwareTypeList" => $this->getFirmwareTypeInfo()));
            }
                break;
        }
    }

    public function listFirmwareTypeAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_LIST: {
                $pageSize = $this->getPost("page_size");
                $pageNumber = $this->getPost("page_number");
                $pageIndex = ($pageNumber - 1) * $pageSize;
                $tableName = "(SELECT * FROM firmware_type ORDER BY id DESC)";
                $result = $this->fetchAll($tableName);
                $this->returnJson($result);
            };
                break;
            case $this::REQUEST_ACTION_UPDATE: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "id",
                        "type" => "presence",
                        "message" => "ID不能为空"),
                    array(
                        "key" => "name",
                        "type" => "presence",
                        "message" => "名称不能为空"),
                ));
                $keyId = $this->getPost("id");
                $sqlId = $this->updateSqlData(array(
                    "table" => "firmware_type",
                    "fieldList" => array("name", "content"),
                    "where" => " id='$keyId' "
                ));
                $this->returnSuccess("更新成功");
            }
                break;
            case $this::REQUEST_ACTION_ADD: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "name",
                        "type" => "presence",
                        "message" => "名称不能为空")
                ));
                $last_id = $this->insertSqlData(array(
                    "table" => "firmware_type",
                    "fieldList" => array("name", "content")
                ));
                if ($last_id >= 0) {
                    $this->returnJson($last_id);
                } else {
                    $this->returnError("添加失败");
                }
            };
                break;
            case $this::REQUEST_ACTION_DELETE: {
                $idList = $this->getPost("id_list");
                $result = $this->deleteAllById("firmware_type", $idList);
                if ($result > 0) {
                    $this->returnSuccess("删除成功！");
                } else {
                    $this->returnError("删除失败！");
                }
            }
                break;
            default: {

            }
                break;
        }
    }

    public function getFirmwareListAction()
    {
        $sqlType = "SELECT * FROM firmware_type";
        $dataType = $this->fetchAll($sqlType);
        foreach ($dataType AS &$item){
            $typeId = $item["id"];
            $item["info"] = $this->fetchAll("SELECT f.id,f.name,f.version,f.url,f.size,f.created_at FROM firmware_version AS f WHERE f.firmware_type_id=$typeId ORDER BY f.created_at DESC");
        }
        if ($dataType){
            $this->returnJson($dataType);
        }else{
            $this->returnError("查询错误");
        }
    }

    public function getLastFirmwareAction()
    {
        $sql = "SELECT id,name,version,url,size,created_at FROM firmware_version ORDER BY created_at DESC LIMIT 15";
        $data = $this->fetchAll($sql);
        if ($data){
            $this->returnJson($data);
        }else{
            $this->returnError("查询错误");
        }
    }

    public function getFirmwareDetailAction()
    {
        $this->checkRequestParams(array(
            array(
                "key" => "id",
                "type" => "presence",
                "message" => "id不存在"),
        ));
        $keyId = $this->getPost("id");
        $data = $this->fetchOne("SELECT * FROM firmware_version WHERE id=$keyId");
        if ($data){
            $this->returnJson($data);
        }else{
            $this->returnError("请求失败");
        }
    }

    public function firmwareDownloadListAction()
    {
        if($this->isLoginFirmwareCenter() == false){
            $this->response->redirect('../firmware/loginFirmwareCenter');
        }
    }

    public function firmwareDetailAction(){
        if($this->isLoginFirmwareCenter() == false){
            $detailId=$this->getQuery("id");
            $this->response->redirect('../firmware/loginFirmwareCenter?id='.$detailId);
        }
    }

    public function firmwareCenterDetailAction()
    {
        if($this->isLoginFirmwareCenter() == false){
            $detailId=$this->getQuery("id");
            $this->response->redirect('../firmware/loginFirmwareCenter?id='.$detailId);
        }
        $id = $this->getQuery("id");
        if ($id){
            $data = $this->fetchOne("SELECT * FROM firmware_version WHERE id=$id");
            $userInfo = $this->fetchOne("SELECT nickname,icon_url FROM user WHERE id={$data["created_user_id"]}");
            if ($userInfo["icon_url"]){
                $icon = $userInfo["icon_url"];
            }else {
                $icon = "/images/main/main_user_icon.png";
            }
            $this->view->setVars(array(
                "data" => $data,
                "icon" => $icon
            ));
        }else{
            $this->return403();
        }
    }

    public function likeFirmwareAction()
    {
        $this->checkRequestParams(array(
            array(
                "key" => "id",
                "type" => "presence",
                "message" => "id不能为空")
        ));
        $id = $this->getPost("id");
        $countData = $this->fetchOne("SELECT `like_count` FROM firmware_version WHERE id=$id");
        $oldCount = intval($countData["like_count"]);
        $count =  $oldCount + 1;
        $this->update("firmware_version", array("like_count"=>$count), "id=$id", false);
        return;
    }

    public function loginFirmwareCenterAction()
    {
        $password = "#feima666";
        if($this->isLoginFirmwareCenter()){
            $this->response->redirect('../firmware/firmwareCenter');
        }else{
            $getPwd = $this->getPost("password");
            if ($getPwd){
                if ($getPwd == $password){
                    $this->session->set($this::SESSION_DOWNLOAD_CENTER, true);
                    $this->returnSuccess("登录成功");
                }else {
                    $this->returnError("密码错误");
                }
            }
        }

    }

    public function loginFirmwareCenterNewAction()
    {

    }

    public function firmwareCenterAction()
    {
        if($this->isLoginFirmwareCenter() == false){
            $this->response->redirect('../firmware/loginFirmwareCenter');
        }
    }


    public function destorySessionAction()
    {
        $this->session->destroy();
    }
}